Merge Two Sorted List

Merge two sorted linked lists and return it as a new list. Problem from LeetCode


In [1]:
class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
        
def mergeTwoLists(l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    if l1 and l2:
        if l1.val > l2.val:
            l1, l2 = l2, l1
        l1.next = mergeTwoLists(l1.next, l2)
    return l1 or l2    

def stringToListNode(input):
    numbers = input
    dummyRoot = ListNode(0) # Convert input list into linked list
    ptr = dummyRoot
    for number in numbers:
        ptr.next = ListNode(number)
        ptr = ptr.next

    ptr = dummyRoot.next
    return ptr

def listNodeToString(node):
    if not node:
        return "[]"

    result = ""
    while node:
        result += str(node.val) + ", "
        node = node.next
    return "[" + result[:-2] + "]"

In [4]:
# Input
line1 = [1,2,4]
line2 = [1,3,4]
l1 = stringToListNode(line1)
l2 = stringToListNode(line2)

In [5]:
# Output
ret = mergeTwoLists(l1, l2)
out = listNodeToString(ret)
out


Out[5]:
'[1, 1, 2, 3, 4, 4]'